package com.szbmyoubao.app.ui.login.forget

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.lifecycle.lifecycleScope
import com.szbmyoubao.app.timer.tickFlow
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.helper.LoginHelper
import com.ellecity06.common.ktx.load
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.databinding.ActivityForgetPwdBinding
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 *@author joe
 *@data 2024/10/29
 *@describe
 */
class ForgetPwdActivity : BaseMvvmActivity<ActivityForgetPwdBinding, ForgetPwdViewModel>(),
    View.OnClickListener {
    override val userBaseTitle: Boolean
        get() = false
    private var mTickJob: Job? = null
    private var type = 0

    companion object {
        fun launch(context: Context, type: Int) {
            context.startActivity(
                Intent(context, ForgetPwdActivity::class.java).putExtra(
                    "type",
                    type
                )
            )
        }
    }

    override fun inflateBinding(): ActivityForgetPwdBinding =
        ActivityForgetPwdBinding.inflate(layoutInflater)

    override fun initialize(savedInstanceState: Bundle?) {
        type = intent.getIntExtra("type", 0)
        if (type == 0) {
            binding.tvTitle.text = "找回账号密码"
        } else {
            binding.tvTitle.text = "设置登录密码"
        }
    }

    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is ForgetPwdState.SmdCodeSuccess -> {
                    ToastUtils.show("验证码已发送")
                    countDown()
                }
                is ForgetPwdState.ForgetPwdSuccess -> {
                    ToastUtils.show("修改成功")
                    if (type == 0) {
                        finish()
                    } else {
                        LoginHelper.instance.logout(this)
                    }

                }
                is ForgetPwdState.GetPicCodeSuccess -> {
                    binding.ivPicCode.load(this, it.url)
                }
            }
        }
    }

    override fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(true)
            titleBar(binding.toolBar)
        }
    }

    override val darkFont: Boolean
        get() = false

    override fun initEvent() {
        binding.etPhone.addTextChangedListener(textWatch)
        binding.ivEye.setOnClickListener(this)
        binding.ivReEye.setOnClickListener(this)
        binding.tvSendTitle.setOnClickListener(this)
        binding.tvConfirm.setOnClickListener(this)
        binding.toolBar.setNavigationOnClickListener { finish() }
        binding.ivPicCode.setOnClickListener(this)
    }

    private val textWatch = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

        override fun afterTextChanged(s: Editable?) {
            if (!s.isNullOrEmpty() && s.toString().length == 11) {
                binding.layoutPicCode.visibility = View.VISIBLE
                lifecycleScope.launch {
                    viewModel.intentChannel.send(ForgetIntent.GetPicCode(s.toString()))
                }
            } else {
                binding.layoutPicCode.visibility = View.GONE
            }
        }

    }


    override fun initData() {
    }

    /**
     * 密码是否可见
     * 1 明文
     */
    private fun setEysSee(editText: EditText, imageView: ImageView) {
        logD("type=${editText.inputType}")
        if (editText.inputType == 1) {
            editText.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT
        } else {
            editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_NORMAL
        }
        setSye(imageView, editText.inputType == 1)
        //光标位置
        editText.setSelection(editText.text.toString().length)
    }

    private fun setSye(imageView: ImageView, isSee: Boolean) {
        imageView.setImageResource(if (isSee) R.mipmap.icon_eye_open else R.mipmap.icon_eye_close)
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.iv_eye -> {
                setEysSee(binding.etPassword, binding.ivEye)
            }
            R.id.iv_re_eye -> {
                setEysSee(binding.etRePassword, binding.ivReEye)
            }
            R.id.tv_send_title -> {
                val imagCode = binding.etPicCode.text.toString().trim()
                val phone = binding.etPhone.text.toString().trim()
                lifecycleScope.launch {
                    viewModel.intentChannel.send(ForgetIntent.SendSmsCode(imagCode, phone))
                }
            }
            R.id.tv_confirm -> {
                toForget()
            }
            R.id.iv_pic_code -> {
                val phone = binding.etPhone.text.toString().trim()
                lifecycleScope.launch {
                    viewModel.intentChannel.send(ForgetIntent.GetPicCode(phone))
                }

            }
        }
    }

    private fun toForget() {
        val phone = binding.etPhone.text.toString().trim()
        val psw = binding.etPassword.text.toString().trim()
        val rePsw = binding.etRePassword.text.toString().trim()
        val code = binding.etSmsCode.text.toString().trim()

        lifecycleScope.launch {
            viewModel.intentChannel.send(ForgetIntent.ForgetPwd(code, psw, rePsw, phone, 1))
        }
    }


    // (函数)，开始倒计时
    private fun countDown() {
        var duration = 60
        mTickJob?.cancel()
        mTickJob = tickFlow {
            duration -= 1
            if (duration <= 0) {
                mTickJob?.cancel()
                // 结束
                binding.tvSendTitle.text = "发送验证码"
                binding.tvSendTitle.isEnabled = true
            } else {
                binding.tvSendTitle.text = "${duration}后重发"
                binding.tvSendTitle.isEnabled = false
            }
        }
    }

    override fun onDestroy() {
        binding.etPhone.removeTextChangedListener(textWatch)
        super.onDestroy()
    }
}